
package com.hockeo.tinygds;

import java.lang.reflect.Field;

import com.google.appengine.api.datastore.Text;
import com.hockeo.tinygds.annotation.TUnindexed;
import com.hockeo.tinygds.error.TNotLoadableException;
import com.hockeo.tinygds.error.TNotPersistableException;

/**
 *
 * @version $Id$
 * @author jjanke
 */
public class TFieldString extends TField<String>
{
  protected TFieldString( TinyGDSFactory factory, Field field )
  {
    super( factory, field );
  }

  @Override
  public Object getValueForDatastore( Object objInstance )
  {
    String str = super.getValue( objInstance );

    // If the string is too long, it must be converted into a Text object. This is only
    // possible if the property has been marked as being unindexed because Text is never
    // indexed by the Google datastore.
    //
    if ( str != null && str.length() > 500 )
      if ( getRealField().isAnnotationPresent( TUnindexed.class ) )
        return new Text( str );
      else
        throw TNotPersistableException.indexedStringPropertyTooLong( getRealField(), str );

    return str;
  }

  @Override
  public void setValueFromDatastore( Object objInstance, Object objDatastoreValue )
  {
    if ( objDatastoreValue instanceof Text )
      setValue( objInstance,  ( (Text) objDatastoreValue ).getValue() );
    else
      setValue( objInstance,  (String) objDatastoreValue );
  }

  @Override
  protected String transformDatastoreValue( Object objDatastoreValue )
  {
    if ( objDatastoreValue instanceof Text )
      return  ( (Text) objDatastoreValue ).getValue();

    throw TNotLoadableException.cannotConvertValue( objDatastoreValue, getRealField() );
  }
}
